<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发起人账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入发起人账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="begin">
        <el-date-picker
          clearable
          v-model="queryParams.begin"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="end">
        <el-date-picker
          clearable
          v-model="queryParams.end"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="活动地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入活动地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务领域" prop="fieldName">
        <el-input
          v-model="queryParams.fieldName"
          placeholder="请输入服务领域"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务对象" prop="targetName">
        <el-input
          v-model="queryParams.targetName"
          placeholder="请输入服务对象"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务场所" prop="venueName">
        <el-input
          v-model="queryParams.venueName"
          placeholder="请输入服务场所"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['volunteer:activity:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['volunteer:activity:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['volunteer:activity:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['volunteer:activity:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动id" align="center" prop="id" />
      <el-table-column label="活动名称" align="center" prop="name" />
      <el-table-column label="发起人账号" align="center" prop="userName" />
      <el-table-column label="招募人数" align="center" prop="recruit" />
      <el-table-column label="图片地址" align="center" prop="imgPath" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imgPath" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="begin" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.begin, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="end" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.end, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余时间(天)" align="center" prop="end" width="180">
        <template slot-scope="scope">
          <span>{{ getDaysUntilEnd(scope.row.end) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动地址" align="center" prop="address" />
      <el-table-column label="服务领域" align="center" prop="fieldName" />
      <el-table-column label="服务对象" align="center" prop="targetName" />
      <el-table-column label="服务场所" align="center" prop="venueName" />
      <el-table-column label="联系人姓名" align="center" prop="contactName" />
      <el-table-column label="联系人电话" align="center" prop="contactPhone" />
      <el-table-column label="活动介绍" align="center" prop="introduction" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['volunteer:activity:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['volunteer:activity:remove']"
          >删除</el-button>
            <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRecruit(scope.row)"
          >招募人员</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRecruit2(scope.row)"
          >查看人员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="招募人数" prop="recruit">
          <el-input v-model="form.recruit" placeholder="请输入招募人数" />
        </el-form-item>
        <el-form-item label="图片地址" prop="imgPath">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/common/upload"
            :headers="{Authorization: bearer}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.imgPath"
              :src="form.imgPath"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="结束日期" prop="end">
          <el-date-picker
            clearable
            v-model="form.end"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="活动地址" prop="address" style="width: 100%">
          <el-input v-model="form.address" placeholder="请输入活动地址" />
        </el-form-item>
        <el-form-item label="服务领域" prop="fieldId">
          <el-select v-model="form.fieldId" clearable placeholder="请选择服务领域" style="width: 100%">
            <el-option
              v-for="item in fieldList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务对象" prop="targetId">
          <el-select v-model="form.targetId" clearable placeholder="请选择服务对象" style="width: 100%">
            <el-option
              v-for="item in targetList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务场所" prop="venueId">
          <el-select v-model="form.venueId" clearable placeholder="请选择服务场所" style="width: 100%">
            <el-option
              v-for="item in venueList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="活动介绍" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 招募报名人员 -->
    <el-dialog :title="title" :visible.sync="recruitOpen" width="500px" append-to-body>
      <el-table v-loading="loading" :data="recruitForm">
      <el-table-column label="报名人员昵称" align="center" prop="nickName" />
      <el-table-column label="活动名称" align="center" prop="activityName" />
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="enableRecruit(scope.row)"
            v-hasPermi="['volunteer:activity:edit']"
          >{{recruitOrFire}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listActivity,
  getActivity,
  delActivity,
  addActivity,
  updateActivity,
  getRecruit,
  recruit
} from "@/api/volunteer/activity";

import { listField } from "@/api/volunteer/field";
import { listTarget } from "@/api/volunteer/target";
import { listVenue } from "@/api/volunteer/venue";

export default {
  name: "Activity",
  data() {
    var validateEnd = (rule, value, callback) => {
      const today = new Date();
      const selectedDate = new Date(value);

      if (today > selectedDate) {
        callback(new Error("结束日期必须距今大于1天"));
      } else {
        callback();
      }
    };
    return {
      // 招募or解雇
      recruitOrFire: '招募',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动管理表格数据
      activityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      recruitOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        userId: null,
        userName: null,
        begin: null,
        end: null,
        address: null,
        fieldId: null,
        fieldName: null,
        targetId: null,
        targetName: null,
        venueId: null,
        venueName: null,
        contactName: null,
        contactPhone: null
      },
      // 表单参数
      form: {},
      recruitForm: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "活动名称不能为空", trigger: "blur" }
        ],
        recruit: [
          { required: true, message: "招募人数不能为空", trigger: "blur" }
        ],
        imgPath: [
          { required: true, message: "图片地址不能为空", trigger: "blur" }
        ],
        end: [{ required: true, validator: validateEnd, trigger: "blur" }],
        address: [
          { required: true, message: "活动地址不能为空", trigger: "blur" }
        ],
        fieldId: [
          { required: true, message: "服务领域id不能为空", trigger: "blur" }
        ],
        targetId: [
          { required: true, message: "服务对象id不能为空", trigger: "blur" }
        ],
        venueId: [
          { required: true, message: "服务场所id不能为空", trigger: "blur" }
        ],
        contactName: [
          { required: true, message: "联系人姓名不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系人电话不能为空", trigger: "blur" }
        ],
        introduction: [
          { required: true, message: "活动介绍不能为空", trigger: "blur" }
        ]
      },
      // 图片地址
      imageUrl: "",
      // token
      bearer: "",
      // 服务领域
      fieldList: [],
      // 服务对象
      targetList: [],
      // 服务场所
      venueList: []
    };
  },
  created() {
    console.log(document.cookie);

    this.getList();
    this.getBearer();
  },
  methods: {
    // 招募 or 解雇
    enableRecruit(row) {
      let id = row.id
      let isRecruited = 1
      if (this.recruitOrFire == '解雇') {
        isRecruited = 0
      }
      
      recruit(id, isRecruited)
      this.handleRecruit(row)
    },
    // 剩余天数
    getDaysUntilEnd(endTime) {
      const currentTime = new Date().getTime();
      const end = new Date(endTime).getTime();
      const diffTime = Math.abs(end - currentTime);
      let day = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      if (day > 0) {
        return day;
      } else {
        return "已结束";
      }
    },
    // 验证结束日期
    validateEnd(rule, value, callback) {
      const today = new Date();
      const selectedDate = new Date(this.endDate);
      if (today <= selectedDate) {
        callback(new Error("结束日期必须距今大于1天"));
      } else {
        callback();
      }
    },
    // 获取token
    getBearer() {
      const cookie = document.cookie;
      this.bearer = "Bearer " + cookie.split("Token=")[1];
    },
    // 图片上传
    handleAvatarSuccess(res, file) {
      this.form.imgPath = res.url;
    },
    beforeAvatarUpload(file) {
      const allowedTypes = ["image/jpeg", "image/png"];
      const isJPG = allowedTypes.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /** 查询活动管理列表 领域 对象 场所列表 */
    getList() {
      this.loading = true;
      listActivity(this.queryParams).then(response => {
        this.activityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listField().then(response => {
        this.fieldList = response.rows;
      });
      listTarget().then(response => {
        this.targetList = response.rows;
      });
      listVenue().then(response => {
        this.venueList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        userId: null,
        recruit: null,
        imgPath: null,
        begin: null,
        end: null,
        address: null,
        fieldId: null,
        targetId: null,
        venueId: null,
        contactName: null,
        contactPhone: null,
        introduction: null,
        isDeleted: null
      };
      this.imageUrl = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getActivity(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改活动管理";
      });
    },
    /** 招募表 */
    handleRecruit(row) {
      this.reset();
      const id = row.id;
      getRecruit(id, 0).then(response => {
        this.recruitForm = response.data;
        this.recruitOpen = true;
        this.recruitOrFire = '招募',
        this.title = "招募报名人员";
      });
    },
    /** 查看已经被招募的人员表 */
    handleRecruit2(row) {
      this.reset();
      const id = row.id;
      getRecruit(id, 1).then(response => {
        this.recruitForm = response.data;
        this.recruitOpen = true;
        this.recruitOrFire = '解雇',
        this.title = "查看已被招募人员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActivity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除活动管理编号为"' + ids + '"的数据项？')
        .then(function() {
          return delActivity(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "volunteer/activity/export",
        {
          ...this.queryParams
        },
        `activity_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>